package com.nowcoder.community.aspect;

import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Aspect
public class ServiceLogAspect {


    private static final Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

    // 通过正则表达式给service包下各个类的方法加入切点声明
    @Pointcut("execution(* com.nowcoder.community.service.*.*(..))")
    public void pointCut() {}


    @Before("pointCut()")
    public void beforeService(JoinPoint joinPoint) {
        // 记录客户端IP地址,访问时间,访问功能
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 特殊的service调用
        // 如kafka consumer中的调用则attributes会为空
        // 那就不添加日志了!
        if(attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            String ip = request.getRemoteHost();
            String accessTime = new SimpleDateFormat("yyyy-MM-ss HH:mm:ss").format(new Date());
            // 类名+方法名
            String accessService = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
            logger.info(String.format("用户:[%s],在[%s],访问了[%s].", ip, accessTime, accessService));
        }
    }

}
